"""
History Recorders window
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import types

import ui_w_historyrecorders
from agent import recorder 
from agent import recorders
import agent
import time
import system.navalasystem as na
from misc import misc
from system import tradezone
import misc.quoteperiod as qp

try:
    _fromUtf8 = QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s


class HistoryRecorders(QMainWindow, ui_w_historyrecorders.Ui_HistoryRecorders):
    def __init__(self, parent=None):
        super(HistoryRecorders, self).__init__(parent)
        self.setupUi(self)
        self.AddItems()
        self.resize(1, 1) # As small as possible!

    @misc.CatchException
    def StartAgent(self, s):
        agent_ = eval("recorders.recorder_{0}()".format(s))
        try:
            agent_.flagReinitiate = True
            agent_.Start()
        except Exception as E:
            QMessageBox.critical(self,"Failed to start agent", E.message)
            raise

    @misc.CatchException
    def CreateCustomAgent(self):
        name = str(self.lineEditName.text())
        stockNames = eval(str(self.lineEditNames.text()))
        table = [1]+range(qp.daily, qp.yearly+1) # These are the numeric quote periods corresponding to the items inside the combo box
        period = table[self.comboBoxPeriod.currentIndex()]
        sPeriod = qp.data[period]["varname"].capitalize()
        
        r = eval("recorder.%sRecorder(name='%s')" % (sPeriod, name))
        r.SetNames2(stockNames)
        r.infoGetter = tradezone.GetHTTPClientProxy()
        r.Reinitiate() # Puts a reinitiate message in process inQueue
        try:
            r.Start()
        except Exception as E:
            QMessageBox.critical(self,"Failed to start agent", E.message)
            raise

    def AddItems(self):
        a = zip(*recorders._aa)[1]
        
        for (i, s) in enumerate(a):
            code = """
self.label{0} = QLabel(self.centralwidget)
self.label{0}.setObjectName("label{0}")
self.label{0}.setText("{0}")
self.gridLayout.addWidget(self.label{0}, {1}, 0, 1, 1)
self.pushButton{0} = QPushButton(self.centralwidget)
self.pushButton{0}.setObjectName("pushButton")
self.pushButton{0}.setText("Attempt start")
self.gridLayout.addWidget(self.pushButton{0}, {1}, 1, 1, 1)

def on_pushButton{0}_clicked(self):
    print "Button {0} clicked"
    self.StartAgent("{0}")

self.on_pushButton{0}_clicked = types.MethodType(on_pushButton{0}_clicked, self, 
                                                 self.__class__) # bound method
                                                 
self.connect(self.pushButton{0}, SIGNAL("clicked()"), 
             self.on_pushButton{0}_clicked)
""".format(s, i)
            exec(code)

        #QMetaObject.connectSlotsByName(self)
    
    @misc.CatchException
    @pyqtSignature("bool")
    def on_pushButtonStart_clicked(self, checked):
        self.CreateCustomAgent()

